use sea_orm::{
    ColumnTrait, DatabaseConnection, DbErr, DeleteResult, EntityTrait, Order, QueryFilter,
    QueryOrder, TryIntoModel,
};
use sky_pojo::{dto, entities::shopping_cart};

pub async fn insert(
    db: DatabaseConnection,
    model: shopping_cart::ActiveModel,
) -> Result<shopping_cart::Model, DbErr> {
    shopping_cart::Entity::insert(model)
        .exec_with_returning(&db)
        .await
}

pub async fn update_number_by_id(
    db: DatabaseConnection,
    model: shopping_cart::ActiveModel,
) -> Result<shopping_cart::Model, DbErr> {
    let dto = model.clone().try_into_model().unwrap();
    shopping_cart::Entity::update(model)
        .filter(shopping_cart::Column::Id.eq(dto.id))
        .exec(&db)
        .await
}

pub async fn list(
    db: DatabaseConnection,
    mut model: shopping_cart::ActiveModel,
) -> Result<Vec<shopping_cart::Model>, DbErr> {
    let mut query = shopping_cart::Entity::find();

    if let Some(user_id) = model.user_id.take() {
        query = query.filter(shopping_cart::Column::UserId.eq(user_id));
    }
    if let Some(dish_id) = model.dish_id.take() {
        query = query.filter(shopping_cart::Column::DishId.eq(dish_id));
    }

    if let Some(setmeal_id) = model.setmeal_id.take() {
        query = query.filter(shopping_cart::Column::SetmealId.eq(setmeal_id));
    }
    if let Some(dish_flavor) = model.dish_flavor.take() {
        query = query.filter(shopping_cart::Column::DishFlavor.eq(dish_flavor));
    }

    query = query.order_by(shopping_cart::Column::CreateTime, Order::Desc);

    query.all(&db).await
}

pub async fn delete_by_user_id(
    db: &DatabaseConnection,
    user_id: i64,
) -> Result<DeleteResult, DbErr> {
    shopping_cart::Entity::delete_many()
        .filter(shopping_cart::Column::UserId.eq(user_id))
        .exec(db)
        .await
}

pub async fn delete_by_id(db: &DatabaseConnection, id: i64) {
    shopping_cart::Entity::delete_by_id(id)
        .exec(db)
        .await
        .unwrap();
}

pub async fn insert_batch(
    db: &DatabaseConnection,
    models: Vec<shopping_cart::ActiveModel>,
) -> Result<sea_orm::InsertResult<shopping_cart::ActiveModel>, DbErr> {
    shopping_cart::Entity::insert_many(models).exec(db).await
}
